package com.ilovepostcard.data;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

import com.ilovepostcard.utils.Constants;

import android.graphics.Bitmap;

public class OffLinePostcard {
	
	
	public final static String TAG_IMAGE = "image";
	public final static String TAG_COMMENT="comment";
	public final static String TAG_LOCATION="location";
	public final static String TAG_DATE="date";
	public final static String TAG_TAGS="tags";
	public final static String TAG_SHOWLOCATION="isshowLoaction";
	public final static String TAG_CANBEFOUND="canbefound";
	public final static String TAG_LATITUDE="latitude";
	public final static String TAG_LONGITUDE="longitude";
	public final static String TAG_USERID = "userid";
	
	
	final static String TAG_ROOT="OfflineInformation";
	final static String INFORMATIONFILE = "info.xml";
	final static String IMAGEFILE = "image.jpg";
	final static String OffLineRoot = Constants.APP_DIR+"offline/";
	String name;
	
	public OffLinePostcard()
	{
		name = createNewOffLinePC();
	}
	
	public OffLinePostcard(String name)
	{
		this.name = name;
		
	}
	
	public String getName()
	{
		return name;
	}
	
	private String createNewOffLinePC()
	{
		Date now = new Date();
		SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss"); 
		String time=df.format(now);
		File newOffline =new File(OffLineRoot+time);
		newOffline.mkdir();

		return time;
	}
	
	private String getRootPath()
	{
		File root = new File(OffLineRoot);
		if(!root.exists())
			root.mkdir();
		
		if(name == null)
			name = createNewOffLinePC();
		
		String folder = OffLineRoot+name;
		File test =new File(folder);
		if(!test.exists())
			test.mkdir();
		return folder;
	}
	
	private void callWriteXmlFile(Document doc, Writer w, String encoding) 
	{
		  try {
		   Source source = new DOMSource(doc);

		   Result result = new StreamResult(w);

		   Transformer xformer = TransformerFactory.newInstance().newTransformer();
		   xformer.setOutputProperty(OutputKeys.ENCODING, encoding);
		   xformer.transform(source, result);
		  } catch (TransformerConfigurationException e) {
		   e.printStackTrace();
		  } catch (TransformerException e) {
		   e.printStackTrace();
		  }
		 }
	private void output(Node node, String filename) {
	    TransformerFactory transFactory = TransformerFactory.newInstance();
	    try {
	      Transformer transformer = transFactory.newTransformer();
	      transformer.setOutputProperty("encoding", "UTF-8");
	      transformer.setOutputProperty("indent", "yes");
	      DOMSource source = new DOMSource();
	      source.setNode(node);
	      StreamResult result = new StreamResult();
	      if (filename == null) {
	        result.setOutputStream(System.out);
	      } else {
	        result.setOutputStream(new FileOutputStream(filename));
	      }
	      transformer.transform(source, result);
	    } catch (TransformerConfigurationException e) {
	      e.printStackTrace();
	    } catch (TransformerException e) {
	      e.printStackTrace();
	    } catch (FileNotFoundException e) {
	      e.printStackTrace();
	    }
	  }


	public void save(String tag, String msg)
	{
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = null;
		try {
			   builder = dbf.newDocumentBuilder();
			  } catch (Exception e) {
			}
		Document doc = null;
		Element root = null;
		File xmlFile = new File(getRootPath()+"/"+INFORMATIONFILE);
		if(!xmlFile.exists())
		{
		    doc = builder.newDocument();
			root = doc.createElement(TAG_ROOT);
			doc.appendChild(root); 
		}
		else
		{
			try {
				doc = builder.parse(xmlFile);
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			root = doc.getDocumentElement();
		}
		  
		  
		  Element name = doc.createElement(tag);
		  root.appendChild(name);
		  Text tname = doc.createTextNode(msg);
		  name.appendChild(tname);

		  try {
			   FileOutputStream fos = new FileOutputStream(getRootPath()+"/"+INFORMATIONFILE);
			   OutputStreamWriter outwriter = new OutputStreamWriter(fos);
			   //callWriteXmlFile(doc, outwriter, "UTF-8");
			   output(root,getRootPath()+"/"+INFORMATIONFILE);
			   outwriter.close();
			   fos.close();
			  } catch (Exception e) {
			   e.printStackTrace();
			  }

	}
	
	public void saveImage(Bitmap bitmap)
	{
		
		File noScan =new  File(getRootPath()+"/"+".nomedia");
		try {
			noScan.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		File f = new File(getRootPath()+"/" + IMAGEFILE);

		try {
			f.createNewFile();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		FileOutputStream fOut = null;
		try {
			fOut = new FileOutputStream(f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		if(fOut != null)
		{
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
			try {
				fOut.flush();
			} catch (IOException e) {
			e.printStackTrace();
			}
			try {
				fOut.close();
			} catch (IOException e) {
			e.printStackTrace();
			}
		}
		
	}
	
	public String getImagePath()
	{
		return getRootPath()+"/" + IMAGEFILE;
	}
	
	public String get(String tag)
	{
		
	   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	   DocumentBuilder builder;
	   Document doc ;
	   Element root = null;

		try {
			builder = dbf.newDocumentBuilder();
			doc = builder.parse(new File(getRootPath()+"/"+INFORMATIONFILE));
			root = doc.getDocumentElement();
			NodeList list = root.getElementsByTagName(tag);
			
			 for (int i = 0;i<list.getLength();i++) {
				 Element e = (Element) list.item(i);
				 if(e != null)
					 return e.getTextContent();
		        }


		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		 return null;
		 

	}
	

}
